//
// import './scss/index.scss';
//

$(document).ready(function () {
  $.ajax({
    type: "post",
    url: "getImageVerifyCode",
    dataType: "text",
    success: function (img, status) {
      alert(img);
      $("#checkImg").attr("src", "data:image/png;base64," + img);
    },
    error: function (data) {
      alert('响应失败！');
    }
  });
});

function SlideCaptcha(obj) {
  this.slideBox = null
  this.defaultPoint = {}
  this.getImageUrl = ''
  this.validCheck = ''
  this.randomNo = parseInt(Math.random() * 10000000)
  this.id = obj.id
  this.init(obj)
  this.validation = false
  this.width = obj.width
  this.height = obj.height
}

// Init the SlideCaptcha
SlideCaptcha.prototype.init = function(obj) {
  //
  this.getImageUrl = obj.getResource
  this.validCheck = obj.validCheck
  this.defaultPoint.x = obj.defaultPoint.x
  this.defaultPoint.y = obj.defaultPoint.y
  this.slideBox = document.getElementById(obj.id)
  this.id = obj.id
  //
  this.slideBox.classList.add('slideCaptcha')
  //
  this.getImage(this.randomNo).then(data => {
    // console.log(data.data);
    this.spiritUrl = data.data.newImage
    this.slideBgUrl = data.data.oriCopyImage
    this.defaultPoint.x = 0
    this.defaultPoint.y = data.data.yPoint
    return this.imageLoad(this.slideBgUrl)
  }).then(data => {
    //
    this.slideBgBoxCreate()
    this.slideBgDraw(data)
    this.refreshImageBg()
    //

    function autoImageRefresh(_this) {
      //
      const refresh = setTimeout(() => {
        //
        const refreshBtn = document.getElementById(_this.id + '_imageReload')
        if (refreshBtn) {
          refreshBtn.dispatchEvent(new Event('click'))
          autoImageRefresh(_this)
          clearTimeout(refresh)
          clearTimeout(parentRefresh)
        } else {
          clearTimeout(refresh)
        }
      }, 600 * 1000)
      // autoImageRefresh()
    }
    const parentRefresh = setTimeout(() => {
      autoImageRefresh(this)
    }, 600 * 1000)
    //
    //
    return this.imageLoad(this.spiritUrl)
  }).then(data => {
    this.slideSpiritDraw(data)
    //
    this.slidebarCreate()
    //
    this.successStatusAdd()
    //
    this.dragEventInit()
  })
  //
  // console.log(this)
}

// Get the image data, data type is base64
SlideCaptcha.prototype.getImage = function(parmas) {
  const params = parmas
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('post', this.getImageUrl, true)
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        const res = JSON.parse(xhr.response)
        resolve(res)
      }
    }
    xhr.send(JSON.stringify({ flowId: params }))
  })
}

// Global method to generate the image tag with url
SlideCaptcha.prototype.imageLoad = function(url) {
  return new Promise((resolve, reject) => {
    const image = new Image()

    image.src = 'data:image/png;base64,' + url
    image.onload = function() {
      resolve(image)
    }
  })
}

// To generate a image background tag in the box after the function prototype.slideBgBoxCreate()
SlideCaptcha.prototype.slideBgDraw = function(image) {
  // console.log(123)
  const bg = document.getElementById(this.id + '_slideBoxImage')
  if (bg) {
    bg.appendChild(image)
    bg.replaceChild(image, bg.children[0])
  } else {
    const slideBg = document.createElement('div')
    slideBg.setAttribute('id', this.id + '_slideBoxImage')
    slideBg.classList.add('slideBoxImage')
    slideBg.appendChild(image)
    //
    document.getElementById(this.id + '_slideBg').appendChild(slideBg)
    this.slideContainerSizeSet(image.clientWidth, image.clientHeight)
    this.boxWidth = image.clientWidth
    this.boxHeight = image.clientHeight
    document.getElementById(this.id + '_slideBg').classList.add('hide')
  }
}

// To generate a box tag for image background;
SlideCaptcha.prototype.slideBgBoxCreate = function() {
  const slideBg = document.createElement('div')
  slideBg.setAttribute('id', this.id + '_slideBg')
  //
  slideBg.classList.add('slideBg')
  //
  this.slideBox.appendChild(slideBg)
}

// Refresh the image, recall the ajax to get random image from API;
SlideCaptcha.prototype.refreshImageBg = function() {
  // console.log(this.obj.defaultPoint)
  const img = document.getElementById(this.id + '_slideBoxImage').children[0]
  const _that = this
  const reload = document.createElement('span')
  reload.setAttribute('id', this.id + '_imageReload')
  reload.classList.add('imageReload')
  //
  const close = document.createElement('span')
  close.setAttribute('id', this.id + '_close')
  close.classList.add('captcha-close')
  close.addEventListener('click', function(e) {
    document.getElementById(_that.id + '_slideBg').classList.add('hide')
  })
  //
  let spiritUrl, slideBgUrl
  //
  function resetFn() {
    _that.randomNo = parseInt(Math.random() * 10000000)
    _that.getImage(_that.randomNo).then(data => {
      // console.log(data.data);
      spiritUrl = data.data.newImage
      slideBgUrl = data.data.oriCopyImage
      _that.defaultPoint.x = 0
      _that.defaultPoint.y = data.data.yPoint
      //
      return _that.imageLoad(slideBgUrl)
    }).then(data => {
      _that.slideBgDraw(data)
      return _that.imageLoad(spiritUrl)
    }).then(data => {
      //
      _that.slideSpiritDraw(data)
    })
  }
  //
  reload.addEventListener('click', resetFn)
  //
  document.getElementById(this.id + '_slideBg').appendChild(reload)
  document.getElementById(this.id + '_slideBg').appendChild(close)
}
// The spirit box image generate
SlideCaptcha.prototype.slideSpiritDraw = function(image) {
  //
  const slideSpirit = document.getElementById(this.id + '_slideSpirit')

  if (slideSpirit) {
    slideSpirit.replaceChild(image, slideSpirit.children[0])
    slideSpirit.style.left = this.defaultPoint.x + 'px' || 0
    slideSpirit.style.top = this.defaultPoint.y + 'px'
  } else {
    const spiritDiv = document.createElement('span')
    spiritDiv.setAttribute('id', this.id + '_slideSpirit')
    spiritDiv.classList.add('slideSpirit')
    spiritDiv.appendChild(image)
    spiritDiv.style.left = this.defaultPoint.x + 'px' || 0
    spiritDiv.style.top = this.defaultPoint.y + 'px'
    const slideBg = document.getElementById(this.id + '_slideBg')
    slideBg.appendChild(spiritDiv)
  }
}
// To generate the slide icon and the background in the slidebar in the slide box;
SlideCaptcha.prototype.slidebarCreate = function() {
  //
  const slidebar = document.getElementById(this.id + '_slideBar')
  if (!slidebar) {
    const bar = document.createElement('div')
    bar.setAttribute('id', this.id + '_slideBar')
    bar.setAttribute('class', 'slideBar')
    //
    const slideCircle = document.createElement('span')
    slideCircle.setAttribute('id', this.id + '_slideBarCircle')
    slideCircle.classList.add('slideBarCircle')
    bar.appendChild(slideCircle)
    //
    this.slideBox.appendChild(bar)
    //
  }
}
// To create a success status box after slide to the correct position;
SlideCaptcha.prototype.successStatusAdd = function() {
  //
  const successStatus = document.createElement('div')
  successStatus.setAttribute('id', this.id + '_successBg')
  successStatus.classList.add('successBg')
  successStatus.innerHTML = `
		<span>验证成功</span>
	`
  successStatus.style.height = this.height + 'px'
  document.getElementById(this.id + '_slideBg').appendChild(successStatus)
  const successText = document.createElement('div')
  successText.setAttribute('id', this.id + '_successText')
  successText.classList.add('successText')
  successText.innerHTML = `
		<span class="success-arrow"></span>
		<span class="success-text"> 拖动滑块完成验证 </span>
		<span class="success-arrow"></span>
	`
  document.getElementById(this.id + '_slideBar').appendChild(successText)
  //
}
// mouseDown, mouseMove, mouseUp event init.
SlideCaptcha.prototype.dragEventInit = function() {
  //
  const _that = this
  //
  const slideCircle = document.getElementById(this.id + '_slideBarCircle')
  const slideSpirit = document.getElementById(this.id + '_slideSpirit')
  let startX
  let dragX
  //
  slideCircle.addEventListener('mousedown', mouseDown)
  //
  function mouseDown(e) {
    startX = e.clientX
    document.body.addEventListener('mousemove', mouseMove)
    document.body.addEventListener('mouseup', mouseUp)
    //
    document.getElementById(_that.id + '_slideBg').classList.remove('hide')
  }
  //
  function mouseMove(e) {
    // console.log(e)
    if (e.clientX - startX > 0 && e.clientX - startX < document.getElementById(_that.id + '_slideBg').clientWidth - document.getElementById(_that.id + '_slideSpirit').clientWidth + 5) {
      if (startX) {
        moveCalc(slideCircle, startX, e.clientX)
        //
        moveCalc(slideSpirit, startX, e.clientX)
      }
    }
  }
  //
  function moveCalc(target, startX, moveX) {
    //
    dragX = moveX - startX
    target.style.left = dragX + 'px'
  }
  //
  function mouseUp(e) {
    document.body.removeEventListener('mousemove', mouseMove)
    document.body.removeEventListener('mouseup', mouseUp)
    // console.log (_that.validCheck)
    _that.validCheckFn(dragX).then(data => {
      if (data.status === 0) {
        document.getElementById(_that.id + '_successBg').classList.add('success')
        const removeStatus = setTimeout(function() {
          document.getElementById(_that.id + '_successBg').classList.remove('success')
          clearTimeout(removeStatus)
          document.getElementById(_that.id + '_successText').classList.add('success')
          // document.querySelector('.success-text').innerHTML = ''
          document.getElementById(_that.id + '_successText').children[1].innerHTML = ''
          slideCircle.style.left = (document.getElementById(_that.id + '_slideBar').clientWidth - 40) + 'px'
          // document.getElementById('slideBg').remove()
          // _that.slideBox.removeChild(document.getElementById(_that.id + '_slideBg'));
          document.getElementById(_that.id + '_slideBg').classList.add('hide')
          _that.validation = true
        }, 500)
        //
        slideCircle.removeEventListener('mousedown', mouseDown)
        //
      } else {
        resetPoint()
      }
    })
  }
  //
  function resetPoint() {
    slideCircle.style.left = 0
    slideSpirit.style.left = 0
  }
}
// To check the slide vliadation when mouseup, it will call the ajax and send the corridiate X;
SlideCaptcha.prototype.validCheckFn = function(pointX) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('post', this.validCheck, true)
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        const res = JSON.parse(xhr.response)
        resolve(res)
      }
    }
    xhr.send(JSON.stringify({ flowId: this.randomNo, xPoint: parseInt(pointX) }))
  })
  //
}
// To set the slide box height after get the image Background;
SlideCaptcha.prototype.slideContainerSizeSet = function(w, h) {
  this.slideBox.style.width = this.width + 'px'
}
//
SlideCaptcha.prototype.slideCaptchaReload = function() {
  this.defaultPoint.x = 0
  this.refreshImageBg()
  this.dragEventInit()
  // console.log(document.getElementById(this.id + '_imageReload'));
  document.getElementById(this.id + '_slideBarCircle').style.left = 0
  document.getElementById(this.id + '_successText').classList.remove('success')
  document.querySelector('.success-text').innerHTML = '拖动滑块完成验证'
  this.validation = false
  document.getElementById(this.id + '_imageReload').dispatchEvent(new Event('click'))
}
//
export const slideCaptcha = function(obj) {
  return new SlideCaptcha(obj)
}

